﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;

namespace Helpers.Validation
{
    public class MinMaxRule : ValidationRule
    {
        private double min;
        private double max;
        private DoubleRangeChecker validRange = null;
        private bool decimalPlaces = true; 

        public MinMaxRule()
        {
        }

        public DoubleRangeChecker ValidRange
        {
            get { return validRange; }
            set { validRange = value; }
        }

        public double Min
        {
            get { return min; }
            set { min = value; }
        }

        public double Max
        {
            get { return max; }
            set { max = value; }
        }

        public bool DecimalPlaces
        {
            get { return decimalPlaces; }
            set { decimalPlaces = value; }
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            double paramMin; double paramMax; 
            double number = 0;

            if (validRange != null)
            {
                paramMin = Double.Parse(validRange.Minimum);
                paramMax = Double.Parse(validRange.Maximum);
            }
            else
            {
                paramMin = min;
                paramMax = max; 
            }

            bool validNumber = Double.TryParse((string) value, out number);
            if (!validNumber) return new ValidationResult(false, "Invalid number.");

            if (!DecimalPlaces)
            {
                if (number % 1 != 0) return new ValidationResult(false, "Invalid number: the value can't have decimal places."); 
            }

            if ((number < paramMin) || (number > paramMax))
            {
                return new ValidationResult(false,
                  "Please enter a number in the range: " + paramMin + " - " + paramMax + ".");
            }
            else
            {
                return new ValidationResult(true, null);
            }
        }
    }

    public class DoubleRangeChecker : DependencyObject
    {
        public String Minimum
        {
            get { return (String)GetValue(MinimumProperty); }
            set { SetValue(MinimumProperty, value); }
        }
        public static readonly DependencyProperty MinimumProperty =
            DependencyProperty.Register("Minimum", typeof(string), typeof(DoubleRangeChecker), new UIPropertyMetadata(""));


        public String Maximum
        {
            get { return (String)GetValue(MaximumProperty); }
            set { SetValue(MaximumProperty, value); }
        }
        public static readonly DependencyProperty MaximumProperty =
            DependencyProperty.Register("Maximum", typeof(string), typeof(DoubleRangeChecker), new UIPropertyMetadata(""));

    }

}
